<template>
  <div class="tree" id="tree123">
    <div style='padding:5px;'>
      <el-input
        placeholder="搜索部门"
        v-model="value"
        prefix-icon="el-icon-search"
        clearable>
      </el-input>
    </div>
    <el-tree
      :data="treeData"
      :filter-node-method="filterNode"
      :props="obj"
      accordion
      @current-change="handleCheckChange"
      ref="tree"
    >
    </el-tree>
  </div>
</template>

<script>
import {getDepts} from '@/api/unTreeSelect.js'
export default {
  data() {
    return {
      value: '',
      obj:{children:'children', label:'name', key:'id', id: 'id' }
    };
  },
  watch: {
    value(value) {
      if(value == ''){
        this.$emit('selDepartment',value);
      }
      this.$refs.tree.filter(value)
    }
  },
  computed:{
    treeData:{
      get(){
        return this.$store.state.broadTreeData
      },
      set(val){
        this.$store.state.broadTreeData = val
      }
    }
  },
  created() {
    if(!this.treeData){
      getDepts().then(res=>{
        this.treeData = this.optionData(res.data)
      })
    }
  },
  mounted(){
    document.addEventListener('mousedown',this.closeFn)
  },
  beforeDestroy(){
    document.removeEventListener('mousedown',this.closeFn)
  },
  methods:{
    optionData(data){
      let cloneData = JSON.parse(JSON.stringify(data))      // 对源数据深度克隆
      return  cloneData.filter(father=>{                       // 循环所有项，并添加children属性
          let branchArr = cloneData.filter(child=>father.id == child.parentid);       // 返回每一项的子级数组
          branchArr.length>0 ? father.children=branchArr : ''   //给父级添加一个children属性，并赋值
          father.label = father.name
          return father.parentid==0;      //返回第一层
      });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    handleCheckChange(data, checked, indeterminate) {
      if(checked){
        this.$emit('selDepartment',data);
      }else{
        this.$emit('selDepartment','');
      }
    },
    closeFn(e){
      var domTree = document.querySelector('#tree123')
      console.log('点击==>',domTree,e.target)
      if(domTree && !domTree.contains(e.target)){
        this.$emit('closeTree')
      }
    }
  },
};
</script>
<style lang="less" scoped>
.tree{
  z-index: 1;
  background-color: #fff;
  position: absolute;
  top: 38px;
  left: -2px;
  box-shadow: 0 1px 6px rgba(0,0,0,.2);
  /deep/ .el-tree{
    height: 300px;
    overflow: scroll;
    padding-right: 2px;
  }
  /deep/ .el-input__inner{
    line-height: 30px;
  }
  /deep/ .el-input__icon{
    line-height: 30px;
  }
} 
</style>